package xyz.jcat.web.security.annotation;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.method.AbstractFallbackMethodSecurityMetadataSource;

import java.lang.reflect.Method;
import java.util.Collection;

/**
 * 自定义权限注解权限标识处理类
 */
public class AuthAnnotationMethodSecurityMetadataSource extends AbstractFallbackMethodSecurityMetadataSource {

    @Override
    protected Collection<ConfigAttribute> findAttributes(Method method, Class<?> targetClass) {
        RequiresAuthentication requiresAuthentication = method.getAnnotation(RequiresAuthentication.class);
        if(requiresAuthentication != null) {
            return PermissionSecurityConfig.loginOnly();
        }
        RequiresPermission requiresPermission = method.getAnnotation(RequiresPermission.class);
        if(requiresPermission != null) {
            return PermissionSecurityConfig.permissions(requiresPermission.value());
        }
        return findAttributes(targetClass);
    }

    @Override
    protected Collection<ConfigAttribute> findAttributes(Class<?> clazz) {
        RequiresAuthentication requiresAuthentication = clazz.getAnnotation(RequiresAuthentication.class);
        if(requiresAuthentication != null) {
            return PermissionSecurityConfig.loginOnly();
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }
}
